﻿
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;
using System.Text;
namespace UpdateServers.Command
{
    /// <summary>
    /// JSON转换扩展类
    /// </summary>
    public static class JsonConver
    {
        /// <summary>
        /// 将实体对象转为Json字符串
        /// </summary>
        /// <param name="value">对象</param>
        /// <returns>JSON字符串</returns>
        public static string ToJsonString(this object value, String DateTimeFormat = "yyyy/MM/dd HH:mm:ss")
        {
            string result = null;
            if (value != null)
            {
                IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
                timeFormat.DateTimeFormat = DateTimeFormat;
                result = Newtonsoft.Json.JsonConvert.SerializeObject(value, timeFormat);
            }
            return result;

        }

        /// <summary>
        /// 将字符串转化为对象
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="json">JSON字符串</param>
        /// <returns>对象</returns>
        public static T JsonToObject<T>(this string json)
        {
            var result = default(T);
            try
            {
                result = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
            }
            catch (Exception e)
            {
                throw e;

            }
            return result;
        }

    }
}
